#include <math.h>

#include "citizen.hpp"
#include "city.hpp"
#include "foreach.hpp"
#include "formula_callable.hpp"
#include "government.hpp"
#include "raster.hpp"
#include "unit.hpp"
#include "unit_type.hpp"

unit::unit(const_unit_type_ptr type, government_ptr owner, city_ptr home, citizen_ptr c)
  : type_(type), owner_(owner), home_(home), citizen_(c), movement_left_(0), selected_(false)
{}

unit::~unit()
{
}

void unit::new_turn()
{
	movement_left_ = total_movement();
}

void unit::draw(int x, int y)
{
	graphics::blit_texture(type_->texture(), x, y);

	if(selected_) {
		++selected_;
		glBlendFunc(GL_SRC_ALPHA, GL_ONE);
		glColor4f(1.0, 1.0, 1.0, 0.4 + sin(selected_/10.0)*0.25);
		graphics::blit_texture(type_->texture(), x, y);
		glColor4f(1.0, 1.0, 1.0, 1.0);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}
}

void unit::set_loc(const hex::location& loc)
{
	loc_ = loc;
	unshroud();
}

int unit::total_movement() const
{
	return type_->movement();
}

int unit::movement_left() const
{
	return movement_left_;
}

void unit::deplete_movement(int amount)
{
	movement_left_ -= amount;
}

void unit::disband()
{
	home_->tile().citizens().push_back(citizen_);
}

void unit::unshroud()
{
	if(!owner_) {
		return;
	}

	owner_->unshroud(loc_.x(), loc_.y());
	hex::location adj[6];
	get_adjacent_tiles(loc_, adj);
	foreach(const hex::location& a, adj) {
		owner_->unshroud(a.x(), a.y());
	}
}
